package cn.westv.scps.web.controller.sysuser;

import cn.westv.scps.domain.SysUserEntity;
import cn.westv.scps.service.sys.user.ISysUserService;
import cn.westv.scps.utils.MD5Util;
import cn.westv.scps.web.controller.base.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Administrator on 2017/08/10.
 */
@Controller
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController<SysUserController> {
    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping("/home.cgi")
    public String toHomePage() {
        return "forward:/index.jsp";
    }


    /**
     * 登录
     * @param account
     * @param password
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/login")
    public Map<String, Object> userLogin(String account, String password, HttpServletResponse response,
                                               HttpServletRequest request) throws Exception {
        String ip = super.getIpAddr();
        HttpSession session = request.getSession();
        SysUserEntity user = null;
        String encodePsw = MD5Util.getMD5Code(password);
        user = sysUserService.userLogin(account,encodePsw);
        if(user == null ){

            return ajaxReturnMap(OP_STATUS_FAILD, "用户名或密码错误", null);
        }
        user.setLastLoginIp(ip);
        sysUserService.update(user);
        user.setPassword(null);
        session.setAttribute(AbstractController.SESSION_USER_INFO, user);
        return ajaxReturnMap(OP_STATUS_SUCCESS,"登录成功",null);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/logout")
    public Map<String,Object> userLogout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute(AbstractController.SESSION_USER_INFO, null);
        return  ajaxReturnMap(OP_STATUS_SUCCESS,"",null);
    }



}
